package com.ugoodtech.mdcc.client.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.controller.RequestObject.StationCustomerReportObject;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.AliSmsProvider;
import com.ugoodtech.mdcc.client.service.UserLogService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.domain.TechColorAuditingReports.TechColorAuditingReports;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.WechatService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(description = "客户满意度报告相关接口")
@RestController
@RequestMapping("/customerSatisfactionReport")
public class CustomerSatisfactionReportController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CustomerSatisfactionReportController.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private StationCustomerReportRepository stationCustomerReportRepository;

    @Autowired
    private CustomerRegularReportRepository customerRegularReportRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private AliSmsProvider aliSmsProvider;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private UserLogService userLogService;

    @ApiOperation("创建客户满意度报告--改")
    @RequestMapping(value = "createReport", method = RequestMethod.POST)
    public JsonResponse createReport(@ApiIgnore Principal principal,
                                     @RequestBody StationCustomerReportObject stationCustomerReportList,
                                     @ApiParam("常规服务报告的ID") @RequestParam(value = "regularReportId", required = false) Long regularReportId,
                                     @ApiParam("报告状态:complete") @RequestParam(value = "reportType") String reportType) {
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        if (!clientUser.getUserType().equals(UserType.customer)) {
            return JsonResponse.errorResponseWithError("抱歉", "您不是客户,无法填写满意度调查问卷");
        }
        try {
            List<StationCustomerReport> stationCustomerReports = stationCustomerReportList.getStationCustomerReportList();
            JsonResponse jsonResponse = toComplete(clientUser, stationCustomerReports, reportType, regularReportId);
            if (jsonResponse.isSuccess()) {
                try {
                    StationReport regularReport = stationReportRepository.findOne(regularReportId);
                    //创建日志================================
                    userLogService.addUserLog(clientUser, regularReport.getStation().getStationNum(), regularReportId, Constants.SERVICE_REPORT, LogConstants.operate_type_add, LogConstants.business_type_customer_report, null, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return jsonResponse;
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResponse.errorResponseWithError("抱歉", "创建失败");
        }
    }

    private JsonResponse toComplete(User user, List<StationCustomerReport> stationCustomerReports, String reportType, Long regularReportId) {
        StationReport regularReport = stationReportRepository.findOne(regularReportId);
        if (regularReport == null) {
            logger.info("没有此报告ID");
            return JsonResponse.errorResponseWithError("抱歉", "未找到这次的常规服务报告");
        } else if (!regularReport.getCategory().equals(Constants.SERVICE_REPORT)) {
            logger.info("此报告ID不是常规服务报告");
            return JsonResponse.errorResponseWithError("抱歉", "此报告不是常规服务报告");
        }
        Station station = null;
        if (regularReport.getStation() == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到您的维修站");
        } else {
            station = regularReport.getStation();
        }
//        if (!user.getStationId().equals(station.getId())) {
//            return JsonResponse.errorResponseWithError("抱歉", "这份常规服务报告不是当前用户的");
//        }
        StationReport stationReport = new StationReport();
        for (StationCustomerReport customerReport : stationCustomerReports) {
            if (customerReport.getQuestionId().equals(155)) {
                stationReport.setServiceTypAnswerIds(customerReport.getAnswerId());
            }
        }
        stationReport.setStation(station);
        stationReport.setUser(user);
        stationReport.setReportType(reportType);
        stationReport.setCategory(Constants.CUSTOMER_REPORT);
        stationReportRepository.save(stationReport);

        QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qCustomerRegularReport.deleted.eq(false));
//        builder.and(qCustomerRegularReport.enabled.eq(true));
        builder.and(qCustomerRegularReport.contactUser.id.eq(user.getId()));
        builder.and(qCustomerRegularReport.regularReport.id.eq(regularReportId));
        CustomerRegularReport customerRegularReport = customerRegularReportRepository.findOne(builder);
        customerRegularReport.setCustomerReport(stationReport);
        customerRegularReport.setType(true);
        Integer score = 0;
        boolean isbellowSixTy = false;
        for (StationCustomerReport report : stationCustomerReports) {
            report.setStationReport(stationReport);
            score += getScore(report);
            if (StringUtils.isNotEmpty(report.getAnswerId())) {
                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(report.getAnswerId()));
                if (!answerOption.getName().equals("100%") && !answerOption.getName().equals("80%")) {
                    isbellowSixTy = true;
                }
            }
            stationCustomerReportRepository.save(report);
        }

        logger.info("总分数为：" + score);
        score = score / 7;
        logger.info("平均分为：" + score);
        if (score != 100 && !isbellowSixTy) {
            logger.info("满意度报告分有打分包含80分，60分，将报告标示为满分");
            customerRegularReport.setScoreType(2);
        }
        if (score == 100) {
            logger.info("满意度报告分数为满分，将报告标示为满分");
            customerRegularReport.setScoreType(1);
        }
        customerRegularReport.setScore(score.toString());
        customerRegularReportRepository.save(customerRegularReport);
        if (isbellowSixTy) {
            logger.info("满意度报告中有一项低于等于60分，执行发送短信/微信流程,并将此报告标示为60分及以下的报告");
            customerRegularReport.setScoreType(3);
            customerRegularReportRepository.save(customerRegularReport);
            try {
                String customer = "";
                UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
                if (userProfile != null && StringUtils.isNotEmpty(userProfile.getRealName())) {
                    customer = userProfile.getRealName();
                }
                String name = "";
                User regularUser = customerRegularReport.getRegularReport().getUser();
                userProfile = userProfileRepository.findByUserId(regularUser.getId());
                if (userProfile != null && StringUtils.isNotEmpty(userProfile.getRealName())) {
                    name = userProfile.getRealName();
                }
                String serviceTypeId = customerRegularReport.getRegularReport().getServiceTypAnswerIds();
                StringBuffer stringBuffer = new StringBuffer("");
                if (StringUtils.isNotEmpty(serviceTypeId)) {
                    String[] str = serviceTypeId.split(",");
                    for (String s : str) {
                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(s));
                        if (answerOption.getId().equals(191L)) {
                            stringBuffer = new StringBuffer("漆星服务");
                            break;
                        }
                        stringBuffer.append(answerOption.getName() + ",");
                    }
                }
                logger.info("<<<<<<<<<<<<<<<<<<开始发送>>>>>>>>>>>>>>>>>");
                logger.info("外勤人员为：" + name);
                logger.info("维修站为：" + station.getName());
                logger.info("维修站iD为：" + station.getId());
                logger.info("服务目标为：" + stringBuffer.toString());
                QUser qUser = QUser.user;
                builder = new BooleanBuilder();
                builder.and(qUser.deleted.eq(false));
                builder.and(qUser.enabled.eq(true));
                builder.and(qUser.authorities.any().name.eq("CUSTOMER_MANAGE"));
                List<User> userList = (List<User>) userRepository.findAll(builder);
                String serviceStr = stringBuffer.toString();
                if (!serviceStr.equals("漆星服务")) {
                    serviceStr = serviceStr.substring(0, serviceStr.length() - 1);
                }
                Map<String, User> userMap = new HashMap<>();
                for (User user1 : userList) {
                    userMap.put(user1.getOpenId(), user1);
                }
                logger.info("---------------------------开始推送微信---------------------------");
                String firstData = "您好，在" + station.getName() + "进行的" + serviceStr + "的常规服务报告，" + customer + "已进行满意度打分，其中至少有一项打分低于60分";
                for (Map.Entry<String, User> userEntry : userMap.entrySet()) {
                    wechatService.pushWechatMessage(userEntry.getValue(), "sPL21Oj3MEQjKjGS-GDHQFC_L5Ngiz4zLxsRcYEXAcc", Constants.WECHAT_PUSH_URL, firstData,
                            "请尽快查看并处理", name, stationReport.getUpdateTimeStr(), "满意度分数低于60分", "", "");
                }
                logger.info("---------------------------推送微信成功---------------------------");
                userRepository.save(user);
            } catch (Exception e) {
                logger.info("<<<<<<<<<<<<<<<<<<发送失败>>>>>>>>>>>>>>>>>!");
                e.printStackTrace();
                return JsonResponse.errorResponseWithError("fail", "发送通知失败");
            }
        }
        return JsonResponse.successResponse();
    }

    private Integer getScore(StationCustomerReport report) {
        String score = questionAnswerOptionRepository.findOne(Long.valueOf(report.getAnswerId())).getName();
        score = score.replace("%", "");
        Integer integerList = Integer.valueOf(score);
        logger.info("此次的值为：" + integerList);
        return integerList;
    }

    @ApiOperation("获取需要填写的客户满意度报告列表--改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "getCustomerReportList", method = RequestMethod.GET)
    public JsonResponse getCustomerReportList(@ApiIgnore Principal principal, Pageable pageable) {
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        if (!clientUser.getUserType().equals(UserType.customer)) {
            return JsonResponse.errorResponseWithError("抱歉", "您不是客户,无法填写满意度调查问卷");
        }
        QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qCustomerRegularReport.deleted.eq(false));
        builder.and(qCustomerRegularReport.enabled.eq(true));
        builder.and(qCustomerRegularReport.type.eq(false));
        builder.and(qCustomerRegularReport.regularReport.contactUser.eq(clientUser.getUsername()));
        Sort sort = new Sort(Sort.Direction.DESC, "creationTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<CustomerRegularReport> regularReports = customerRegularReportRepository.findAll(builder, pageable);
        List<TechColorAuditingReports> toResponseReport = toResponseReport(regularReports.getContent());
        Page<TechColorAuditingReports> page = new PageImpl(toResponseReport, pageable, regularReports.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    private List<TechColorAuditingReports> toResponseReport(List<CustomerRegularReport> regularReports) {
        List<TechColorAuditingReports> responseReports = new ArrayList<>();
        for (CustomerRegularReport customerRegularReport : regularReports) {
            TechColorAuditingReports report = new TechColorAuditingReports();
            StationReport regularServiceReport = customerRegularReport.getRegularReport();
            if (regularServiceReport.getServiceTypAnswerIds() != null) {
                String[] ids = regularServiceReport.getServiceTypAnswerIds().split(",");
                StringBuffer stringBuffer = new StringBuffer("");
                for (String id : ids) {
                    if (StringUtils.isNotEmpty(id)) {
                        QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                        if (questionAnswerOption != null&&questionAnswerOption.getName()!=null) {
                            stringBuffer.append(questionAnswerOption.getName() + ",");
                        }
                    }
                }
                report.setTarget(stringBuffer.toString());
            } else {
                report.setTarget("");
            }
            if (customerRegularReport.getRegularReport().getStation() != null) {
                report.setCity(customerRegularReport.getRegularReport().getStation().getProvince() +
                        customerRegularReport.getRegularReport().getStation().getCity());
                report.setStationName(customerRegularReport.getRegularReport().getStation().getName());
            } else {
                report.setCity("");
                report.setStationName("");
            }
            report.setDateTime(customerRegularReport.getCreationTimeStr());

            UserProfile userProfile = userProfileRepository.findByUserId(regularServiceReport.getUser().getId());
            if (userProfile != null) {
                if (StringUtils.isNotEmpty(userProfile.getRealName())) {
                    report.setUserName(userProfile.getRealName());
                } else {
                    report.setUserName("");
                }
            } else {
                report.setUserName("");
            }

            report.setId(regularServiceReport.getId());
            responseReports.add(report);
        }
        return responseReports;
    }


}
